package com.sinopec.basemodule.launchcontract

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentResultListener
import androidx.lifecycle.LifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter

/**
 * create by lwj
 *
 *
 * 一个轮子
 * 设置值获取值 契约 fragment
 *
 */
class SetAndGetValueFragmentContract<Req>(
    private val getSet: GetSetFromBundle<Req>,
    private val targetPath: String
) {

    /**
     * 任务-跟进信息列表Fragment
     * 数据接收器
     */
    fun receive(
        fragmentManager: FragmentManager,
        lifecycleOwner: LifecycleOwner,
        onResult: (req: Req?) -> Unit
    ) {
        fragmentManager.setFragmentResultListener(
            targetPath, lifecycleOwner,
            FragmentResultListener { requestKey, result ->
                onResult(getSet.get(result))
            })
    }

    /**
     * 任务-跟进信息列表Fragment
     * 数据发射器
     */
    fun send(
        fragmentManager: FragmentManager,
        req: Req
    ) {
        val bundle = Bundle()
        getSet.set(req,bundle)
        fragmentManager.setFragmentResult(
            targetPath,
            bundle
        )
    }

    fun createFragment(): Fragment {
        return ARouter.getInstance()
            .build(targetPath)
            .navigation()
                as Fragment
    }
}